﻿#region 文件信息

/*----------------------------------------------------------------
//
// 文件名称：
// 文件功能描述：
// 设计要求：
//
// 文 件 名：    ServerBootStartUp
// 创建者：      杨程
// 创建日期：	    2022/12/15 12:46:00

//----------------------------------------------------------------*/

#endregion






using Microsoft.OpenApi.Models;

namespace Vampirewal.Admin.Server.ViewModel;

/// <summary>
/// 启动类
/// </summary>
public partial class ServerBootStartUp : VampirewalMiniApiBootStartup
{
    protected override string FirstViewKey => ServerViewKeys.MainView;

    public override void Configure(IApplicationBuilder app)
    {
        //启用静态文件
        app.UseStaticFiles();

        if (!Directory.Exists($"{AppDomain.CurrentDomain.BaseDirectory}Files"))
            Directory.CreateDirectory($"{AppDomain.CurrentDomain.BaseDirectory}Files");

        //使用文件目录，类似FTP
        app.UseDirectoryBrowser(new DirectoryBrowserOptions()
        {
            FileProvider = new PhysicalFileProvider($"{AppDomain.CurrentDomain.BaseDirectory}Files"),
            RequestPath = "/Upload"
        });

        //启用内置全局异常捕获中间件
        app.UseVampirewalMiniApiExceptionHandler();

        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "MiniApi");

            c.EnablePersistAuthorization();
        });

        app.UseVampirewalCoreScheduledTask();
    }

    //public override void OnAppExit(bool IsRun)
    //{
    //    base.OnAppExit(IsRun);
    //}

    //public override void OnAppRun(bool IsRun)
    //{
    //    base.OnAppRun(IsRun);
    //}

    protected override void RegisterService(IServiceCollection services)
    {
        services.AddVampirewalCoreConfig($"{AppDomain.CurrentDomain.BaseDirectory}AppConfig.json", options =>
        {
            options.RegisterOptions<DbBaseOptions>();
            options.RegisterOptions<PagingOptions>();

            options.RegisterOptions<EnvironmentOptions>();
            options.RegisterOptions<FileStorageOptions>();

            options.RegisterOptions<VampirewalMiniApiOptions>();
        });
        services.AddVampirewalCoreDialogMessage();
        //services.AddSingleton<IVampirewalCoreDialogMessage, VampirewalCoreDialogService>();
        //services.AddSingleton<IVampirewalCoreDataContext, AdminServerDataContext>();
        services.UseVampirewalCoreSqlSugar<AdminSqlSugarSetup>();
        services.AddTransient(typeof(SqlSugarRepository<>));
        services.AddSingleton<IVampirewalOperationExcelService, VampirewalOperationExcelService>();
        services.AddSingleton<IVampirewalCoreLogService, AdminLogService>();
        services.AddSingleton<IVampirewalCoreValidationService,VampirewalCoreValidationService>();
        services.AddVampirewalCoreEventBusFactory();
        services.AddTouchSocket();

        #region [     启用webapi功能     ]

        services.AddSingleton<IProblemDetailsWriter, VampirewalMiniApiResultProblemDetailsWriter>();//这个不是很好用，但是还是保留

        services.AddSingleton<IVampirewalMiniApiResultProvider, MiniApiProvider>();

        services.AddEndpointsApiExplorer();

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Title = "测试MiniApi-V1",
                Version = "v1",
                Description = "haha"
            }
            );
            //设置xml引用
            var filePath = Path.Combine(System.AppContext.BaseDirectory, "Vampirewal.Admin.Server.ViewModels.xml");
            c.IncludeXmlComments(filePath);

            //添加授权
            var schemeName = "Bearer";
            c.AddSecurityDefinition(schemeName, new OpenApiSecurityScheme
            {
                In = ParameterLocation.Header,
                Description = "请输入不带有Bearer的Token",
                Name = "Authorization",
                Type = SecuritySchemeType.Http,
                Scheme = schemeName.ToLowerInvariant(),
                BearerFormat = "JWT"
            });
            c.AddSecurityRequirement(new OpenApiSecurityRequirement {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = schemeName,

                            }
                        },
                        new string[0]
                    }
                });
        });

        #endregion

        services.AddVampirewalCoreScheduledTask(option =>
        {
            option.Register<LogJobService>(job =>
            {
                job.JobName = "日志定期清理";
                job.JobDescription = "定时处理日志，每天0点执行一次，每次查出7天前的进行删除";
                job.CronExpression = "0 0 0 * * *";
                job.RetryCount = 3;
            });
        });
    }
}

public class MiniApiProvider: IVampirewalMiniApiResultProvider
{
    public async Task<ApiResult> OnErrorResultProvider(string data, int statusCode)
    {
        ApiResult result = new ApiResult()
        {
            IsSuccess = false,
            Code = statusCode,
            Message = data,
            Time = DateTime.Now,
        };

        return await Task.FromResult(result);
    }

    public async Task<Microsoft.AspNetCore.Http.IResult> OnResponseResultProvider(object data, int statusCode)
    {

        Vampirewal.Core.MiniApi.ApiResult<object> result = new Vampirewal.Core.MiniApi.ApiResult<object>()
        {
            Data = data,
            IsSuccess = true,
            Code = statusCode,
            Time = DateTime.Now,
        };

        return await Task.FromResult(Results.Json(result));

    }
}